package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
@Service
public class UserLoginServiceimpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    /**
     * 登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1 参数校验
        if (dto==null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        // 根据用户名精确查询有效的用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS)
        );
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_ISNTOEXIT_ERROR );
        }
        // 比对密码
        // 数据库密码
        String dbPwd = adUser.getPassword();
        String password = dto.getPassword();
        String salt = adUser.getSalt();

        //加密规则password+salt

        String saltPwd = password+salt;
        String digestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        System.out.println("digestPwd = " + digestPwd);
        if (!dbPwd.equals(digestPwd)){
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NAMEORPWD_ERROR );
        }

        //3 更新数据库登录时间

        adUser.setLoginTime(new Date());
        updateById(adUser);
        //4 返回结果
        // 生成Token

        HashMap<String, Object> resultMap = new HashMap<>();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        resultMap.put("token",token);
        // 用户信息
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user", adUser);
        return ResponseResult.okResult(resultMap);
    }
}
